package com.macro.mall.task;

import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.mapper.CmsContentMapper;
import com.macro.mall.model.CmsContent;
import com.macro.mall.service.CmsContentService;
import com.macro.mall.service.RcRegistrationContentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.List;

/**
 * @author super
 * @title: TaskProcessor
 * @description: TODO 订单关闭处理器
 * @date 2020/9/22 11:02
 */


@Slf4j
@Configuration
@EnableScheduling
public class ContentStatusTaskProcessor {

    private static final String KEY = "CONTENT_STATUS";
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CmsContentService cmsContentService;
    @Autowired
    private CmsContentMapper cmsContentMapper;
    /** RcRegistrationContentService服务 */
    @Autowired
    private RcRegistrationContentService rcRegistrationContentService;
    @Scheduled(cron = "0 0 1 * * ?")
    public void orderClose() {
        log.info(new Date() + "  >>cron执行-修改内容状态定时任务启动 Timer begin...");
        try {
            ValueOperations objOps = redisTemplate.opsForValue();
            boolean bSet = objOps.setIfAbsent(KEY, "processing");
            if (!bSet) {
                String message = "processor is running, cannot start again.";
                log.error(message + " the key is redis is :" + KEY);
                return;
            }
            List<CmsContent> cmsContents = cmsContentService.find(null);
            for (CmsContent value : cmsContents) {
                if (value.getEtime().getTime() < value.getStime().getTime()) {
                    Asserts.fail("合同开始时间应晚于结束时间");
                }
                long l = System.currentTimeMillis();
                if (value.getStime().getTime() < l && value.getEtime().getTime() > l) {
                    value.setStatus("4");
                } else {
                    value.setStatus("1");
                }
                int result = 0;
                try {
                    result = cmsContentMapper.updateNotNullCmsContentById(value);
                } catch (Exception e) {
                    log.error("", e);
                    Asserts.fail(ResultCode.FAILED);
                }
            }
        } catch (Exception e) {
            log.error("CONTENT_STATUS __Close ~~~~~~~~~~~~~~~~~~~~~~~~~~", e);
        } finally {
            log.info(new Date() + "  >>cron执行-修改内容状态定时任务启动 Timer end.");
            Boolean delete = redisTemplate.delete(KEY);
        }

    }

}
